'use strict';
const db = uniCloud.database()
const newsCollection = db.collection('news')

exports.main = async (event, context) => {
  const { page = 1, pageSize = 10 } = event
  
  try {
    // 获取新闻列表
    const { data, err } = await newsCollection
      .orderBy('createTime', 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get()
    
    if (err) {
      return {
        errCode: 1,
        errMsg: '获取新闻列表失败'
      }
    }
    
    // 获取总数
    const { total } = await newsCollection.count()
    
    return {
      errCode: 0,
      errMsg: '获取成功',
      data: data.map(item => ({
        id: item._id,
        title: item.title,
        image: item.image,
        date: item.createTime,
        views: item.views || 0,
        summary: item.summary
      })),
      total
    }
  } catch (error) {
    return {
      errCode: 1,
      errMsg: error.message || '获取新闻列表失败'
    }
  }
} 